<?php
class Online_Amazon_Product extends QDB_ActiveRecord_Abstract
{
	/**
	 * 返回对象的定义
	 *
	 * @static
	 *
	 * @return array
	 */
	static function __define()
	{
		return array
		(
			// 指定该 ActiveRecord 要使用的行为插件
			'behaviors' => '',

			// 指定行为插件的配置
			'behaviors_settings' => array
			(
			    # '插件名' => array('选项' => 设置),
			),

			// 用什么数据表保存对象
			'table_name' => 'online_amazon_product',

			// 指定数据表记录字段与对象属性之间的映射关系
			// 没有在此处指定的属性，QeePHP 会自动设置将属性映射为对象的可读写属性
			'props' => array
			(
				// 主键应该是只读，确保领域对象的“不变量”
				'id' => array('readonly' => true),

				/**
				 *  可以在此添加其他属性的设置
				 */
				# 'other_prop' => array('readonly' => true),

				/**
				 * 添加对象间的关联
				 */
				# 'other' => array('has_one' => 'Class'),

			),

			/**
			 * 允许使用 mass-assignment 方式赋值的属性
			 *
			 * 如果指定了 attr_accessible，则忽略 attr_protected 的设置。
			 */
			'attr_accessible' => '',

			/**
			 * 拒绝使用 mass-assignment 方式赋值的属性
			 */
			'attr_protected' => 'id',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值不允许由外部提供
			 *
			 * 这里指定的属性会在创建记录时被过滤掉，从而让数据库自行填充值。
			 */
			'create_reject' => '',

			/**
			 * 指定更新数据库中的对象时，哪些属性的值不允许由外部提供
			 */
			'update_reject' => '',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 如果填充值为 self::AUTOFILL_TIMESTAMP 或 self::AUTOFILL_DATETIME，
			 * 则会根据属性的类型来自动填充当前时间（整数或字符串）。
			 *
			 * 如果填充值为一个数组，则假定为 callback 方法。
			 */
			'create_autofill' => array
			(
				# 属性名 => 填充值
				# 'is_locked' => 0,
			),

			/**
			 * 指定更新数据库中的对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 填充值的指定规则同 create_autofill
			 */
			'update_autofill' => array
			(
			),

			/**
			 * 在保存对象时，会按照下面指定的验证规则进行验证。验证失败会抛出异常。
			 *
			 * 除了在保存时自动验证，还可以通过对象的 ::meta()->validate() 方法对数组数据进行验证。
			 *
			 * 如果需要添加一个自定义验证，应该写成
			 *
			 * 'title' => array(
			 *	array(array(__CLASS__, 'checkTitle'), '标题不能为空'),
			 * )
			 *
			 * 然后在该类中添加 checkTitle() 方法。函数原型如下：
			 *
			 * static function checkTitle($title)
			 *
			 * 该方法返回 true 表示通过验证。
			 */
			'validations' => array
			(
			),
		);
	}


/* ------------------ 以下是自动生成的代码，不能修改 ------------------ */

	/**
	 * 开启一个查询，查找符合条件的对象或对象集合
	 *
	 * @static
	 *
	 * @return QDB_Select
	 */
	static function find()
	{
		$args = func_get_args();
		return QDB_ActiveRecord_Meta::instance(__CLASS__)->findByArgs($args);
	}

	/**
	 * 返回当前 ActiveRecord 类的元数据对象
	 *
	 * @static
	 *
	 * @return QDB_ActiveRecord_Meta
	 */
	static function meta()
	{
		return QDB_ActiveRecord_Meta::instance(__CLASS__);
	}


/* ------------------ 以上是自动生成的代码，不能修改 ------------------ */
	static function getOnlineAmazonProduct($shop_ids, $start_time, $end_time)
	{
		set_time_limit(0);
		$amazon_shops = Shop_API_Amazon::find('shop_api_amazon.shop_id in (' . implode(',', $shop_ids) . ')')
			->joinLeft('shop', 'name', 'shop.id=shop_api_amazon.shop_id')
			->asArray()->getAll();
		$wrong_listing = '';
		foreach ($amazon_shops as $amazon_shop)
		{
			$service_url = 'https://' . $amazon_shop['mws_endpoint'];
			$config = array (
				'ServiceURL' => $service_url,
				'ProxyHost' => $amazon_shop['proxy_host'] ? $amazon_shop['proxy_host'] : null,
				'ProxyPort' => $amazon_shop['proxy_port'] ? $amazon_shop['proxy_port'] : -1,
				'MaxErrorRetry' => 3,
			);
			$service = new MarketplaceWebService_Client(
				$amazon_shop['access_key'],
				$amazon_shop['secret_key'],
				$config,
				$amazon_shop['application_name'],
				$amazon_shop['version']
			);
			$request = new MarketplaceWebService_Model_RequestReportRequest();
			$request->setMarketplaceIdList(array('Id' => array($amazon_shop['marketplace_id'])));
			$request->setMerchant($amazon_shop['merchant_id']);
			if (! empty($start_time) && ! empty($end_time))
			{
				$request->setStartDate($start_time);
				$request->setEndDate($end_time);
			}
			$request->setReportType('_GET_FLAT_FILE_OPEN_LISTINGS_DATA_');
			$response = $service->requestReport($request);
			$request_id = $report_id = '';
			if ($response->isSetRequestReportResult() && $response->getRequestReportResult()->isSetReportRequestInfo())
			{
				$reportRequestInfo = $response->getRequestReportResult()->getReportRequestInfo();
				if ($reportRequestInfo->isSetReportRequestId())
				{
					$request_id = $reportRequestInfo->getReportRequestId();
				}
        	}
        	if ($request_id)
        	{
        		while (empty($report_id))
        		{
        			sleep(40);
	        		$request_list = new MarketplaceWebService_Model_GetReportListRequest();
					$request_list->setMerchant($amazon_shop['merchant_id']);
					$request_list->setMarketplace($amazon_shop['marketplace_id']);
					$request_list->setReportRequestIdList(array($request_id));
					$response_list = $service->getReportList($request_list);
					$getReportListResult = $response_list->getGetReportListResult()->getReportInfoList();
					if ($getReportListResult && $getReportListResult[0]->isSetReportId())
					{
						$report_id = $getReportListResult[0]->getReportId();
					}
        		}
        		$request_report = new MarketplaceWebService_Model_GetReportRequest();
				$request_report->setMerchant($amazon_shop['merchant_id']);
				$request_report->setMarketplace($amazon_shop['marketplace_id']);
				$request_report->setReport(@fopen('php://temp', 'rw+'));
				$request_report->setReportId($report_id);
				$response_report = $service->getReport($request_report);
				$i = 1;
				$products = array();
        		while (($buffer = fgets($request_report->getReport(), 10240)) !== false)
				{
				 	if ($i != 1)
				 	{
				 		if ($data = explode("\t", $buffer))
				 		{
					 		$products[] = array('sku' => trim($data[0]), 'price' => trim($data[2]), 'quantity' => trim($data[3]), 'shop_item_id' => trim($data[1]));
				 		}
				 	}
				 	$i++;
			    }
			    fclose($request_report->getReport());
        		foreach ($products as $p)
		    	{
		    		if (! self::judgeOnlineAmazonProductFormat($p['sku']))
		    		{
		    			$wrong_listing .= $p['sku'] . "\t" . $p['shop_item_id'] . "\t" . $amazon_shop['name'] . "\t\n";
		    			continue;
		    		}
		    		$old_product = Online_Amazon_Product::find('sku=? and shop_id=?', $p['sku'], $amazon_shop['shop_id'])->getOne();
		    		$status = ($p['quantity'] == 0) ? Q::ini('custom_flag/online_amazon_product_status/offsale/value') : Q::ini('custom_flag/online_amazon_product_status/onsale/value');
		    		if ($old_product['id'])
		    		{
			    		$old_product->price = $p['price'];
			    		$old_product->quantity = $p['quantity'];
			    		$old_product->update_time = CURRENT_DATETIME;
			    		$old_product->status = $status;
			    		$old_product->save();
		    		}
		    		else
		    		{
		    			$product_basic = Product_Basic::find('number=?', substr($p['sku'], 0, 7))->asArray()->getOne();
		    			$product_bind = Product_Bind::find('number=?', substr($p['sku'], 0, 7))->asArray()->getOne();
		    			$online_amazon_product = new Online_Amazon_Product();
			    		$online_amazon_product->shop_id = $amazon_shop['shop_id'];
			    		$online_amazon_product->sku = $p['sku'];
			    		$online_amazon_product->shop_item_id = $p['shop_item_id'];
			    		$online_amazon_product->status = $status;
			    		$online_amazon_product->price = $p['price'];
			    		$online_amazon_product->quantity = $p['quantity'];
			    		$online_amazon_product->update_time = CURRENT_DATETIME;
		    			if ($product_basic)
		    			{
		    				$online_amazon_product->product_basic_id = $product_basic['id'];
		    				$online_amazon_product->open_time = $product_basic['create_time'];
		    			}
		    			if ($product_bind)
		    			{
		    				$online_amazon_product->open_time = $product_bind['create_time'];
		    			}
			    		$online_amazon_product->save();
		    		}
		    	}
        	}
		}
		if ($wrong_listing)
    	{
    		$wrong_listing = "错误SKU\t店铺ID\t所在店铺\t\n" . $wrong_listing;
    		$wrong_listing = iconv("UTF-8","UTF-16LE",$wrong_listing);
			$wrong_listing = "\xFF\xFE".$wrong_listing;
			$file_name = date('Y-m-d', CURRENT_TIMESTAMP) . '-' . "Amazon.xls";
			$file = file_put_contents(Q::ini('custom_system/wrong_listing_dir') . $file_name, $wrong_listing);
    	}
		return array('ack' => SUCCESS, 'message' => 'success updateOnlineAmazonProduct, execute time:' . sprintf('%.4f', microtime(true) - $GLOBALS['g_boot_time']) . '(secs)');
	}
	
	static function judgeOnlineAmazonProductFormat($sku)
	{
		$item_number = explode('-', $sku);
		$product_in_db1 = Product_Basic::find('number=?', $item_number[0])->asArray()->getOne();
		$product_bind_in_db1 = Product_Bind::find('number=?', $item_number[0])->asArray()->getOne();
		if ($product_in_db1 || $product_bind_in_db1)
		{
			if (isset($item_number[1]) && $item_number[1])
			{
				$product = explode('X', $item_number[1]);
				$product_in_db2 = Product_Basic::find('number=?', $product[0])->asArray()->getOne();
				$product_bind_in_db2 = Product_Bind::find('number=?', $product[0])->asArray()->getOne();
				if ($product_in_db2 || $product_bind_in_db2)
				{
					return false;
				}
			}
			return true;
		}
		else
		{
			return false;
		}
	}
	
	static function getOnlineAmazonInstantData($shop_id, $data)
	{
		set_time_limit(0);
		foreach ($shop_id as $s)
		{
			$amazon_shop = Shop_API_Amazon::find('shop_id=?', $s)->asArray()->getOne();
			$service_url = 'https://' . $amazon_shop['mws_endpoint'] . '/Products/' . Q::ini('custom_api/amazon_mws_services_order_version');
			$config = array (
				'ServiceURL' => $service_url,
				'ProxyHost' => $amazon_shop['proxy_host'] ? $amazon_shop['proxy_host'] : null,
				'ProxyPort' => $amazon_shop['proxy_port'] ? $amazon_shop['proxy_port'] : -1,
				'MaxErrorRetry' => 3,
			);
			$service = new MarketplaceWebServiceProducts_Client(
				$amazon_shop['access_key'],
				$amazon_shop['secret_key'],
				$amazon_shop['application_name'],
				$amazon_shop['version'],
				$config
			);
			$data_arr = array_chunk($data, 15);
			foreach ($data_arr as $da)
			{
				$request_listing_list = $request_competitive_list = array();
				foreach ($da as $d)
				{
					if ($d['update_competitive_price_time'] < date('Y-m-d', CURRENT_TIMESTAMP))
					{
						$request_competitive_list[] = $d['sku'];
					}
					if ($d['update_listing_price_time'] < date('Y-m-d', CURRENT_TIMESTAMP))
					{
						$request_listing_list[$d['shop_item_id']] = $d['shop_item_id'];
					}
				}
				if ($request_listing_list)
				{
					$request_listing = new MarketplaceWebServiceProducts_Model_GetMyPriceForASINRequest();
					$request_listing->setMarketplaceId($amazon_shop['marketplace_id']);
					$request_listing->setSellerId($amazon_shop['merchant_id']);
					$request_listing->setASINList(array_values($request_listing_list));
					try
					{
						$response_listing = $service->getMyPriceForASIN($request_listing);
						$get_result_list = $response_listing->getGetMyPriceForASINResult();
						foreach ($get_result_list as $get_result)
						{
							if ($get_result->isSetProduct())
							{
								$product = $get_result->getProduct();
								$listing_price_list = $product->getOffers()->getOffer();
								foreach ($listing_price_list as $listing)
								{
									$price = $listing->getBuyingPrice();
									$channel = $listing->getFulfillmentChannel();
									$regular_price = $listing->getRegularPrice()->getAmount();
									$sku = $listing->getSellerSKU();
									$check_in_db = Online_Amazon_Product::find('sku=? and shop_id=?', $sku, $amazon_shop['shop_id'])->getOne();
									if ($check_in_db['id'])
									{
										$check_in_db->listing_price = $price->getListingPrice()->getAmount();
										$check_in_db->listing_price_shipping_fee = $price->getShipping()->getAmount();
										$check_in_db->update_listing_price_time = CURRENT_DATETIME;
										if ($check_in_db['price'] != $regular_price)
										{
											$check_in_db->price = $regular_price;
										}
										if ($channel == 'AMAZON')
										{
											$fba_config = array (
												'ServiceURL' => 'https://' . $amazon_shop['mws_endpoint'] . '/FulfillmentInventory/2010-10-01',
												'ProxyHost' => $amazon_shop['proxy_host'] ? $amazon_shop['proxy_host'] : null,
												'ProxyPort' => $amazon_shop['proxy_port'] ? $amazon_shop['proxy_port'] : -1,
												'MaxErrorRetry' => 3,
											);
											$fba_service = new FBAInventoryServiceMWS_Client(
												$amazon_shop['access_key'],
												$amazon_shop['secret_key'],
												$fba_config,
												$amazon_shop['application_name'],
												'2010-10-01'
											);
											
											$fba_request = new FBAInventoryServiceMWS_Model_ListInventorySupplyRequest();
											$fba_request->setMarketplace($amazon_shop['marketplace_id']);
											$fba_request->setSellerId($amazon_shop['merchant_id']);
											$fba_request->setSellerSkus(array($sku));
											$fba_response = $fba_service->listInventorySupply($fba_request);
											$fba_list = $fba_response->getListInventorySupplyResult()->getInventorySupplyList()->getmember();
											if (isset($fba_list[0]) && $fba_list[0])
											{
												$check_in_db->quantity = $fba_list[0]->getInStockSupplyQuantity();
												$check_in_db->status = Q::ini('custom_flag/online_amazon_product_status/onsale/value');
											}
										}
										$check_in_db->channel = $channel;
										$check_in_db->save();
									}
								}
							}
						}
					}
					catch (MarketplaceWebServiceProducts_Exception $ex)
					{
						return array('ack' => FAILURE, 'message' => $ex->getMessage());
					}
				}
				if ($request_competitive_list)
				{
					$request_competitive = new MarketplaceWebServiceProducts_Model_GetCompetitivePricingForSKURequest();
					$request_competitive->setMarketplaceId($amazon_shop['marketplace_id']);
					$request_competitive->setSellerId($amazon_shop['merchant_id']);
					$request_competitive->setSellerSKUList($request_competitive_list);
					try
					{
						$response_competitive = $service->getCompetitivePricingForSKU($request_competitive);
						$get_result_list = $response_competitive->getGetCompetitivePricingForSKUResult();
						foreach ($get_result_list as $get_result)
						{
							if ($get_result->isSetSellerSKU())
							{
								$sku = $get_result->getSellerSKU();
								if ($get_result->isSetSellerSKU())
								{
									$sku = $get_result->getSellerSKU();
									if ($get_result->isSetProduct())
									{
										$product = $get_result->getProduct();
										$competitive_price_list = $product->getCompetitivePricing()->getCompetitivePrices()->getCompetitivePrice();
										if (isset($competitive_price_list[0]) && $competitive_price_list[0])
										{
											$price = $competitive_price_list[0]->getPrice();
											QDB::getConn()->execute('update online_amazon_product set competitive_price=' . $price->getListingPrice()->getAmount() . ', competitive_price_shipping_fee=' . $price->getShipping()->getAmount() . ', update_competitive_price_time=\'' . CURRENT_DATETIME . '\' where sku=\'' . $sku . '\' and shop_id=' . $amazon_shop['shop_id']);
										}
										else
										{
											QDB::getConn()->execute('update online_amazon_product set update_competitive_price_time=\'' . CURRENT_DATETIME . '\' where sku=\'' . $sku . '\' and shop_id=' . $amazon_shop['shop_id']);
											continue;
										}
									}
								}
							}
						}
					}
					catch (MarketplaceWebServiceProducts_Exception $ex)
					{
						return array('ack' => FAILURE, 'message' => $ex->getMessage());
					}
				}
			}
		}
		return array('ack' => SUCCESS, 'message' => '');
	}
	
	/**
	 * @param 请求的SKU $sku
	 * @param 店铺ID $shop_id
	 */
	static function getMatchingProductForIdRequest($sku, $shop_id)
	{
		set_time_limit(0);
		$amazon_shop = Shop_API_Amazon::find('shop_api_amazon.shop_id=?', $shop_id)
			->joinLeft('shop', 'name', 'shop.id=shop_api_amazon.shop_id')
			->asArray()->getOne();
		$service_url = 'https://' . $amazon_shop['mws_endpoint'] . '/Products/' . Q::ini('custom_api/amazon_mws_services_order_version');
		$config = array (
			'ServiceURL' => $service_url,
			'ProxyHost' => $amazon_shop['proxy_host'] ? $amazon_shop['proxy_host'] : null,
			'ProxyPort' => $amazon_shop['proxy_port'] ? $amazon_shop['proxy_port'] : -1,
			'MaxErrorRetry' => 3,
		);
		$service = new MarketplaceWebServiceProducts_Client(
			$amazon_shop['access_key'],
			$amazon_shop['secret_key'],
			$amazon_shop['application_name'],
			$amazon_shop['version'],
			$config
		);
		$request = new MarketplaceWebServiceProducts_Model_GetMatchingProductForIdRequest();
		$request->setMarketplaceId($amazon_shop['marketplace_id']);
		$request->setSellerId($amazon_shop['merchant_id']);
		$request->setIdType('SellerSKU');
		$request->setIdList(array($sku));
		try
		{
			$data = array();
			$response = $service->getMatchingProductForId($request);
			$get_result_list = $response->getGetMatchingProductForIdResult();
			foreach ($get_result_list as $get_result)
			{
				if ($get_result->isSetId())
				{
					$sku = $get_result->getId();
					if ($get_result->isSetProducts())
					{
						$product = $get_result->getProducts()->getProduct();
						if ($product[0]->isSetSalesRankings())
						{
							$sales_ranking_list = $product[0]->getSalesRankings()->getSalesRank();
							if (isset($sales_ranking_list[0]) && $sales_ranking_list[0])
							{
								$data = array('sales_ranking' => $sales_ranking_list[0]->getRank());
							}
						}
						if ($product[0]->isSetAttributeSets())
						{
							$attributeSets = $product[0]->getAttributeSets();
							$nodeList = $attributeSets->getAny();
							foreach ($nodeList as $domNode)
							{
								$arr = array('title' => '', 'img_url' => '');
								foreach ($domNode->childNodes as $childNode)
								{
									if ($childNode->nodeName == 'ns2:SmallImage')
									{
										$arr['img_url'] = $childNode->nodeValue;
									}
									if ($childNode->nodeName == 'ns2:Title')
									{
										$arr['title'] = $childNode->nodeValue;
									}
								}
							}
							$data = array_merge($data, $arr);
						}
					}
				}
			}
			return array('ack' => SUCCESS, 'data' => $data, 'message' => '');
		}
		catch (MarketplaceWebServiceProducts_Exception $ex)
		{
			return array('ack' => FAILURE, 'message' => $ex->getMessage());
		}
	}
	
	static function search($condition, $cp, $ps)
	{
		$columns = array(
			'online_amazon_product.*',
			'shop.name as shop_name',
			'product_warehouse.sales_trend, product_warehouse.sales_status, product_warehouse.purchase_status, product_warehouse.available_quantity',
			'product_basic.name as product_name, product_basic.number as product_number'
		);
		$where = Online_Amazon_Product::buildSearchWhere($condition);
		if ($cp == 0 && $ps == 0)
		{
			$select = Online_Amazon_Product::find($where)
				->joinLeft('shop', '', 'shop.id=online_amazon_product.shop_id')
				->joinLeft('product_warehouse', '', 'product_warehouse.product_basic_id=online_amazon_product.product_basic_id and product_warehouse.warehouse_id=1')
				->joinLeft('product_basic', '', 'product_basic.id=product_warehouse.product_basic_id')
				->setColumns($columns);
			$pagination = array();
		}
		else
		{
			$select = Online_Amazon_Product::find($where)
				->joinLeft('shop', '', 'shop.id=online_amazon_product.shop_id')
				->joinLeft('product_warehouse', '', 'product_warehouse.product_basic_id=online_amazon_product.product_basic_id and product_warehouse.warehouse_id=1')
				->joinLeft('product_basic', '', 'product_basic.id=product_warehouse.product_basic_id')
				->setColumns($columns)->limitPage($cp, $ps);
			$pagination = $select->getPagination();
		}
		$products = $select->order('online_amazon_product.open_time desc')->asArray()->getAll();
		return array(
			'ack' => SUCCESS,
			'message' => '',
			'data' => $products,
			'pagination' => $pagination
		);
	}
	
	static function buildSearchWhere($condition)
	{
		$where = 'online_amazon_product.update_time>=\'' . date('Y-m-d', CURRENT_TIMESTAMP) . '\'';
		if (isset($condition['shop_user_mapping']))
		{
			$where .= ' and online_amazon_product.shop_id in (\'' . implode('\',\'', $condition['shop_user_mapping']) . '\')';
		}
		if (! empty($condition['quantity_operator1']))
		{
			if (isset($condition['quantity1']))
			{
				$where .= ' and online_amazon_product.quantity' . $condition['quantity_operator1'] . $condition['quantity1'];
			}
		}
		if (! empty($condition['quantity_operator2']))
		{
			if (isset($condition['quantity2']))
			{
				$where .= ' and product_warehouse.available_quantity' . $condition['quantity_operator2'] . $condition['quantity2'];
			}
		}
		if (! empty($condition['number']))
		{
			$number = Q::normalize($condition['number'], ',');
			$where .= ' and online_amazon_product.sku in (\'' . implode('\',\'' , $number) . '\')';
		}
		if (! empty($condition['shop_item_id']))
		{
			$where .= ' and online_amazon_product.shop_item_id=\'' . $condition['shop_item_id'] . '\'';
		}
		if (! empty($condition['number_follow']))
		{
			$where .= ' and (online_amazon_product.sku like \'%' . $condition['number_follow'] . '%\' or product_basic.name like \'%' . $condition['number_follow'] . '%\')';
		}
		if (! empty($condition['status']))
		{
			$listing_status_filter = '0';
			foreach (Q::ini('custom_flag/online_amazon_product_status') as $os)
			{
				if (isset($condition['status'][$os['value']]) && $condition['status'][$os['value']] == $os['value'])
				{
					$listing_status_filter .= ' or online_amazon_product.status=\'' . $os['value'] . '\'';
				}
			}
			$where .= " and ($listing_status_filter)";
		}
		if (! empty($condition['channel']))
		{
			$channel_filter = '0';
			foreach (Q::ini('custom_flag/online_amazon_fulfillment_channel') as $o)
			{
				if (isset($condition['channel'][$o['value']]) && $condition['channel'][$o['value']] == $o['value'])
				{
					$channel_filter .= ' or online_amazon_product.channel=\'' . $o['value'] . '\'';
				}
			}
			$where .= " and ($channel_filter)";
		}
		if ( ! empty($condition['shop_id']))
		{
			$mapping = Shop_User_Mapping::getShopIdByUserId();
			if (is_array($condition['shop_id']))
			{
				$condition['shop_id'] = array_intersect($condition['shop_id'], $mapping);
				$shop = implode(',', $condition['shop_id']);
				$where .= " and online_amazon_product.shop_id in ({$shop})";
			}
			elseif (in_array($condition['shop_id'], $mapping))
			{
				$where .= ' and online_amazon_product.shop_id=\'' . $condition['shop_id'] . '\'';
			}
		}
		if (isset($condition['sales_status']))
		{
			$sales_status_filter = '0';
			foreach (Q::ini('custom_flag/product_sales_status') as $ss)
			{
				if (isset($condition['sales_status'][$ss['value']]) && $condition['sales_status'][$ss['value']] == $ss['value'])
				{
					$sales_status_filter .= ' or product_warehouse.sales_status=' . $ss['value'];
				}
			}
			$where .= ' and (' . $sales_status_filter . ')';
		}
		if (isset($condition['purchase_status']))
		{
			$purchase_status_filter = '0';
			foreach (Q::ini('custom_flag/product_purchase_status') as $ps)
			{
				if (isset($condition['purchase_status'][$ps['value']]) && $condition['purchase_status'][$ps['value']] == $ps['value'])
				{
					$purchase_status_filter .= ' or product_warehouse.purchase_status=' . $ps['value'];
				}
			}
			$where .= ' and (' . $purchase_status_filter . ')';
		}
		if (! empty($condition['start_create_time']))
		{
			$where .= ' and online_amazon_product.open_time>=\'' . $condition['start_create_time'] . '\'';
		}
		if (! empty($condition['end_create_time']))
		{
			$where .= ' and online_amazon_product.open_time<=\'' . $condition['end_create_time'] . ' 23:59:59\'';
		}
		if ( ! empty($condition['product_categories_id']))
		{
			$product_categories_ids = Product_Categories::getOffspringById($condition['product_categories_id']);
			array_push($product_categories_ids, $condition['product_categories_id']);
			$where .= ' and product_basic.product_categories_id in (' . implode(',', $product_categories_ids) . ')';
		}
		if (isset($condition['price_compare']))
		{
			if ($condition['price_compare'])
			{
				$where .= ' and online_amazon_product.competitive_price!=online_amazon_product.listing_price';
			}
			else
			{
				$where .= ' and online_amazon_product.competitive_price=online_amazon_product.listing_price';
			}
		}
		return $where;
	}
}